package org.example.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.example.commmon.R;
import org.example.pojo.Category;
import org.example.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController//controller层的注解
@Slf4j
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;



    @PostMapping
    public R<String> save(@RequestBody Category category){
        categoryService.save(category);
        return R.success("成功");
    }


    //菜系分页查询
    /**
     * 页面发送ajax请求 将分页查询的page，pagesize，name等提交给服务端
     * 服务端调用分页查询的功能
     * 服务端将数据返回给页面
     * 用到MybatisPlusConfig
     *
     */
    /**
     *
     * @param page 第几页
     * @param pageSize 每页面多少跳数据
     *
     * @return
     */
    @GetMapping("/page")
    public R<Page<Category>> page(int page, int pageSize){
        //分页构造器  某一页
        Page<Category> page1=new Page<>(page, pageSize);
        /**
         * 如果后需要用到条件分页
         * 就增加一个条件构造器
         */
        //条件构造器
        LambdaQueryWrapper<Category> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        //传入条件 name
        /**
         * 判断查询条件是否null
         * null时不执行
         */
//        if (name!=null)  lambdaQueryWrapper.like(Category::getName,name);
        //添加排序
        lambdaQueryWrapper.orderByDesc(Category::getSort);

        //执行查询
        categoryService.page(page1,lambdaQueryWrapper);

        return R.success(page1);
    }

    @DeleteMapping
    //http://localhost:8080/category?ids=1397844263642378242
    public R<String> delete(Long ids){
        categoryService.remove(ids);
        return R.success("分类删除成功");
    }
    @PutMapping
//http://localhost:8080/category
    public R<String> update(@RequestBody Category category){
        categoryService.updateById(category);
        return  R.success("修改成功");
    }



    //菜品类型
    // http://localhost:8080/category/list?type=1
    @GetMapping("/list")
    /**
     * type=1传来的数据
     * 但是可以封装为实体类
     * Category.type==type
     *
     */
    public R<List<Category>> list(Category category){
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.eq(category.getType()!=null,Category::getType,category.getType());
        categoryLambdaQueryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(categoryLambdaQueryWrapper);
        return R.success(list);

    }







}
